﻿namespace Finder.Utilities.KeyCapture
{
    /// <summary>
    /// Handles the key hooks.
    /// </summary>
    public static class KeyHooking
    {
        /// <summary>
        /// Key hook holder.
        /// </summary>
        private static readonly HotKey HotKey = new HotKey();

        /// <summary>
        /// Initializes static members of the <see cref="KeyHooking"/> class.
        /// </summary>
        static KeyHooking()
        {
            KeyHook = new KeyboardHook(KeyboardHook.Parameters.PassAllKeysToNextApp);
            KeyHook.KeyIntercepted += KeyHookKeyIntercepted;
        }

        /// <summary>
        /// Occurs when [hot key intercepted].
        /// </summary>
        public static event HotKeyIntercepted HotKeyIntercepted;

        /// <summary>
        /// Gets or sets the key hook.
        /// </summary>
        /// <value>The key hook.</value>
        public static KeyboardHook KeyHook { get; set; }

        /// <summary>
        /// Invokes the hot key intercepted.
        /// </summary>
        /// <param name="key">The hot key.</param>
        public static void InvokeHotKeyIntercepted(HotKey key)
        {
            HotKeyIntercepted handler = HotKeyIntercepted;
            if (handler != null)
            {
                handler(key);
            }
        }

        /// <summary>
        /// Keys the hook key intercepted.
        /// </summary>
        /// <param name="e">The <see cref="Finder.Utilities.KeyCapture.KeyboardHook.KeyboardHookEventArgs"/> instance containing the event data.</param>
        public static void KeyHookKeyIntercepted(KeyboardHook.KeyboardHookEventArgs e)
        {
            if (HotKey.Key1 == null)
            {
                HotKey.Key1 = new HotKeyPart(e.KeyCode, e.KeyName);
            }
            else
            {
                if (HotKey.Key1.KeyCode != e.KeyCode)
                {
                    HotKey.Key2 = new HotKeyPart(e.KeyCode, e.KeyName);
                }
            }

            if (HotKey.IsSet)
            {
                InvokeHotKeyIntercepted(HotKey);
                HotKey.Clear();
            }
        }
    }
}
